package com.example.dmgame.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.dmgame.R;
import com.example.dmgame.adapter.CommentAdapter;
import com.example.dmgame.bean.ChapterCommentListItem;
import com.example.dmgame.utils.JsonAsyncCommentTask;
import com.example.dmgame.utils.JsonAsyncCommentTask.CommentCallback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class CommentActivity extends Activity implements OnClickListener {
	String aid;
	int pageno = 1;
	ListView commentListView;
	CommentAdapter adapter;
	List<ChapterCommentListItem> list;
	
	LinearLayout progressLayout;

	Button submit;
	EditText commentEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chapter_comment_activity);

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		aid = bundle.getString("aid");

		submit = (Button) this.findViewById(R.id.submit);
		commentEdit = (EditText) this.findViewById(R.id.commentEdit);
		submit.setOnClickListener(this);

		list = new ArrayList<ChapterCommentListItem>();
		commentListView = (ListView) this.findViewById(R.id.comment_listview);
		progressLayout = (LinearLayout)this.findViewById(R.id.progressLayoutId);
		adapter = new CommentAdapter(list,
				getApplicationContext());
		Log.i("CommentActivity", "---adapter--->>" + adapter);
		commentListView.setAdapter(adapter);
		loadCommentData();
		
		commentListView.setOnScrollListener(new OnScrollListener() {
			private boolean isBottom = false;
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					break;
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(isBottom){
						pageno++;
						loadCommentData();
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				isBottom = (firstVisibleItem+visibleItemCount)==totalItemCount;
			}
		});
	}

	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what==1){
				//progressLayout.setVisibility(View.VISIBLE);
				list.clear();
				pageno = 1;
				loadCommentData();
				Toast.makeText(CommentActivity.this, "评论成功", 1).show();
			}else{
				Toast.makeText(CommentActivity.this, "评论失败", 1).show();
			}
		}
	};
	public void loadCommentData() {
		JsonAsyncCommentTask task = new JsonAsyncCommentTask(
				new CommentCallback() {

					@Override
					public void sendData(List<ChapterCommentListItem> list) {
						// TODO Auto-generated method stub

						Log.i("CommentActivity", "---list--->>" + list);
						//CommentActivity.this.list.clear();
						CommentActivity.this.list.addAll(list);
						adapter.notifyDataSetChanged();
						progressLayout.setVisibility(View.GONE);
					}
				});
		task.execute(loadCommentGetUrl(aid, pageno));
		progressLayout.setVisibility(View.VISIBLE);
	}

	private String loadCommentGetUrl(String aid, int pageno) {
		return "http://www.3dmgame.com/sitemap/api.php?type=1&aid=" + aid
				+ "&pageno=" + pageno;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String commentMsg = commentEdit.getText().toString();
		submitComment(commentMsg);
		commentEdit.setText("");
	}

	public void submitComment(final String msg) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(
						"http://www.3dmgame.com/sitemap/api.php?type=2");
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				BasicNameValuePair pair1 = new BasicNameValuePair("aid", aid);
				BasicNameValuePair pair2 = new BasicNameValuePair("msg", msg);
				BasicNameValuePair pair3 = new BasicNameValuePair("username",
						"tyw");
				list.add(pair1);
				list.add(pair2);
				list.add(pair3);

				UrlEncodedFormEntity entity;
				HttpResponse response = null;
				try {

					entity = new UrlEncodedFormEntity(list, "utf-8");
					post.setEntity(entity);
					// body = new StringBody(jsonObject.toString());
					// entity.addPart(new FormBodyPart("data", body));
					response = client.execute(post);
					if (response.getStatusLine().getStatusCode() == 200) {
						Log.i("CommentActivity", "---OK2-->>");
						HttpEntity httpEntity = response.getEntity();
						String responseJsonString = EntityUtils
								.toString(httpEntity);
						Log.i("CommentActivity", "---responseJsonString-->>"
								+ responseJsonString);
						JSONObject responseJsonObject = new JSONObject(
								responseJsonString);
						String code = responseJsonObject.getString("code");
						Log.i("CommentActivity", "---code-->>" + code);
						if (code.equals("1")) {
							Log.i("CommentActivity", "---OK3-->>");
							//loadCommentData();
							Message message = handler.obtainMessage(1);
							handler.sendMessage(message);
							Log.i("CommentActivity", "---OK4-->>");
						} else {
							Message message = handler.obtainMessage(0);
							handler.sendMessage(message);
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

}
